using namespace std;
#include <iostream>
#include <unistd.h>
#include<sys/stat.h>
#include<fcntl.h>

int main()
{
    pid_t pid=fork();
    if(pid<0)
    {
        perror("fork");
        exit(1);
    }
    if(pid>0)
    {
        exit(0);
    }
    if(setsid()<0)
    {
        perror("setsid");
        exit(2);
    }
    pid=fork();
    if(pid<0)
    {
        perror("second fork fail");
        exit(3);
    }
    if(pid>0)
    {
        exit(0);
    }
    chdir("/");
    int fd =open("/dev/null",O_RDWR);
    dup2(fd,STDIN_FILENO);
    dup2(fd,STDOUT_FILENO);
    dup2(fd,STDERR_FILENO);
    close(fd);
    while(1)
    {
        FILE* log=fopen("/tmp/daemon.log","a");
        if(log)
        {
            fprintf(log,"Daemon is running,pid:%d\n",getpid());
            fclose(log);
        }
        sleep(5);
    }
    return 0;
}